/*
 * Copyright (c) 2006-2008, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.livejournal;

import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.Enumeration;

import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;

import org.panteleyev.ljapi.LJAccount;
import org.panteleyev.ljapi.LJEvent;
import org.panteleyev.ljapi.LJEventAccessLevel;
import org.panteleyev.ljapi.LJGroup;
import org.panteleyev.swing.BasicDialog;
import org.panteleyev.swing.CheckListCellRenderer;
import org.panteleyev.swing.OkCancelButtonPanel;
import org.panteleyev.swing.SimpleListModel;
import org.panteleyev.swing.SwingFactory;

public class EventAccessLevelDialog extends BasicDialog<JFrame> {
    private LJAccount _account;
    private LJEvent post;
    private LJEventAccessLevel accessLevel;
    private int groupMask;
    private SimpleListModel groupListModel;

    private AbstractAction  publicAction;
    private AbstractAction  privateAction;
    private AbstractAction  friendsAction;
    private AbstractAction  customAction;

    private JList           groupList;
    private JRadioButton    accessPublic;
    private JRadioButton    accessPrivate;
    private JRadioButton    accessFriends;
    private JRadioButton    accessGroups;

    public EventAccessLevelDialog(JFrame parent, LJEvent post, LJAccount account) {
        super(parent);

        _account = account;
        this.post = post;
        this.accessLevel = post.getAccessLevel();
        this.groupMask = post.getGroupMask();

        createActions();
        initComponents();

        createGroupList();
        initButtons();
        pack();
    }

    public EventAccessLevelDialog(JFrame parent, LJEventAccessLevel accessLevel, int groupMask, LJAccount account) {
        super(parent);

        _account = account;
        this.post = null;
        this.accessLevel = accessLevel;
        this.groupMask = groupMask;

        createActions();
        initComponents();

        createGroupList();
        initButtons();
        pack();
    }

    private void createActions() {
        publicAction = new AbstractAction(L10N.EA_DIALOG_PUBLIC_RADIO.s()) {
            @Override
            public void actionPerformed(ActionEvent e) {
                accessLevel = LJEventAccessLevel.PUBLIC;
                groupList.setEnabled(false);
            }
        };

        privateAction = new AbstractAction(L10N.EA_DIALOG_PRIVATE_RADIO.s()) {
            @Override
            public void actionPerformed(ActionEvent e) {
                accessLevel = LJEventAccessLevel.PRIVATE;
                groupList.setEnabled(false);
            }
        };

        friendsAction = new AbstractAction(L10N.EA_DIALOG_FRIENDS_RADIO.s()) {
            @Override
            public void actionPerformed(ActionEvent e) {
                accessLevel = LJEventAccessLevel.FRIENDS;
                groupList.setEnabled(false);
                groupListModel.fireListDataChanged();
            }
        };

        customAction = new AbstractAction(L10N.EA_DIALOG_CUSTOM_RADIO.s()) {
            @Override
            public void actionPerformed(ActionEvent e) {
                accessLevel = LJEventAccessLevel.GROUPS;
                groupList.setEnabled(true);
                groupListModel.fireListDataChanged();
            }
        };
    }

    private void initComponents() {
        setTitle(L10N.EA_DIALOG_TITLE.s());

        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        getContentPane().add(SwingFactory.createPanel(BorderFactory.createEmptyBorder(5, 5, 5, 5), SwingFactory.LAYOUT.BOX_Y,
            accessPublic = new JRadioButton(publicAction),
            accessPrivate = new JRadioButton(privateAction),
            accessFriends = new JRadioButton(friendsAction),
            accessGroups = new JRadioButton(customAction)
        ));

        ButtonGroup group = new ButtonGroup();
        group.add(accessPublic);
        group.add(accessPrivate);
        group.add(accessFriends);
        group.add(accessGroups);
        for (Enumeration<AbstractButton> e = group.getElements(); e.hasMoreElements(); ) {
            AbstractButton b = e.nextElement();
            b.setFocusPainted(false);
            b.setFocusable(false);
            b.setMargin(new Insets(0, 0, 0, 0));
        }

        groupList = new JList();
        groupList.setEnabled(false);
        getContentPane().add(new JScrollPane(groupList));
        getContentPane().add(new OkCancelButtonPanel(this));
        SwingFactory.setAlignmentX(getContentPane(), LEFT_ALIGNMENT);
        pack();
    }

    private void initButtons() {
        switch (this.accessLevel) {
            case PUBLIC:
                accessPublic.setSelected(true);
                break;

            case PRIVATE:
                accessPrivate.setSelected(true);
                break;

            case FRIENDS:
                accessFriends.setSelected(true);
                break;

            case GROUPS:
                accessGroups.setSelected(true);
                groupList.setEnabled(true);
                break;
        }
    }

    public LJEventAccessLevel getAccessLevel() { return this.accessLevel; }
    public int getGroupMask() { return this.groupMask; }

    private void createGroupList() {
        groupList.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    int index = groupList.getSelectedIndex();
                    if (index != -1) {
                        LJGroup group = _account.getGroup(index);
                        if (group != null) {
                            groupMask ^= 1 << group.getNumber();
                            groupListModel.fireListDataChanged();
                        }
                    }
                }
            }
        });

        groupList.setCellRenderer(new CheckListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean hasFocus) {
                LJGroup group = _account.getGroup(index);
                if (group != null) {
                    setText(group.getName());
                    if ((groupMask & (1 << group.getNumber())) != 0) {
                        setSelected(true);
                    } else {
                        setSelected(false);
                    }
                }

                setBackground(isSelected ? list.getSelectionBackground() : Color.WHITE);
                setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
                setEnabled(list.isEnabled());
                setFont(list.getFont());
//                setBorder(hasFocus ? focusBorder : noFocusBorder);
                return this;
            }
        });

        groupListModel = new SimpleListModel() {
            @Override
            public Object getElementAt(int index) { return null; }
            @Override
            public int getSize() { return _account.getGroupsCount(); }
        };

        groupList.setModel(groupListModel);
    }

    @Override
    public void onOk() {
        if (post == null) {
            super.onOk();
            return;
        }

        if (this.accessLevel == LJEventAccessLevel.GROUPS) {
            post.setGroupMask(this.groupMask);
        } else {
            post.setAccessLevel(this.accessLevel);
        }
        super.onOk();
    }

}
